//
//  GroupChatViewController.m
//  YMRTC
//
//  Created by admin on 2022/4/8.
//

#import "GroupSelectMemberViewController.h"
#import <Masonry/Masonry.h>
#import <UIKit/UIKit.h>
#import "ContactTableCell.h"
#import "UIViewController+HUD.h"

@interface GroupSelectMemberViewController () <UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSArray *resultKeys;
@property (nonatomic, strong) NSDictionary *resultSectionDict;
@property (nonatomic, strong) UIButton *confirmBtn;
@property (nonatomic,strong)UIView *searchView;
@property (nonatomic,strong)NSIndexPath *lastIndexPath;
@property (nonatomic,strong)NSString *friendId;
@property (nonatomic,strong)NSString *friendName;
@end

@implementation GroupSelectMemberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择成员";
    [self initView];
    [self loadData];
    self.dataArray = [NSMutableArray array];
    
    
}

- (void)initView {
    [self.view addSubview:self.tableView];
    
    CGRect tableFrame = self.tableView.frame;
    
    CGFloat removeHeight = (!self.hidesBottomBarWhenPushed ? self.tabBarController.tabBar.frame.size.height : 0);
    tableFrame.size.height -= removeHeight;
    
    if (@available(iOS 11.0, *)) {
        CGFloat adjustTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top == 0 ? 0 : 20;
        CGFloat removeHeight = [YMIMKitUtils isHairHead]  ? 64 + adjustTop : 64;
        tableFrame.size.height -= removeHeight;
    } else {
        tableFrame.size.height -= 64;
    }
    self.tableView.frame = tableFrame;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
                                                  initWithCustomView:self.confirmBtn];
    
}


- (void)loadData {
    
    
    [[YMIMClient sharedClient].chatManager getConversationWithTargetId:self.groupId completion:^(YMConversation * _Nonnull conversation, YMErrorCode code) {
     
        [self.dataArray removeAllObjects];

//
//        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
//        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        NSMutableArray *array = [NSMutableArray array];
        array = [conversation valueForKey:@"userList"];
        for (int i = 0; i<array.count; i++) {
            
            YMFriendInfo *info = [[YMFriendInfo alloc]init];
            YMGroupUserInfo *userInfo = array[i];
            info.friendId = userInfo.userId;
            info.friendName = userInfo.userName;
            info.friendAvatar = userInfo.userAvatar;
            [self.dataArray addObject:info];
            
        }
        [self sortAndRefreshWithList:self.dataArray];
        
    }];
    


}


- (void)sortAndRefreshWithList:(NSArray *)friendList {
    NSDictionary *resultDic = [[YMIMKitUtils sortedArrayWithPinYinDic:friendList] copy];
   
    self.resultKeys = resultDic[@"allKeys"];
    self.resultSectionDict = resultDic[@"infoDic"];
    [self.tableView reloadData];
}



/**
 确认选择
 */
- (void)confirmAction {
    NSArray *indexArray = self.tableView.indexPathsForSelectedRows;
    if (indexArray.count == 0) {
        [self showHint:@"请选择其他联系人"];
        return;
    }
    
    NSMutableArray *userArray = @[].mutableCopy;
    for (int i= 0; i<indexArray.count; i++) {
        NSIndexPath *indexPath = indexArray[i];
        
        NSString *letter = self.resultKeys[indexPath.section];
        NSArray *array = self.resultSectionDict[letter];
        
        YMFriendInfo *userInfo = array[indexPath.row];
        [userArray addObject:userInfo];
     
    }
    
    !self.didSelectResultBlock ?: self.didSelectResultBlock(userArray);
}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.resultKeys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *letter = self.resultKeys[section];
    NSInteger rows = [self.resultSectionDict[letter] count];
    return rows;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ContactTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContactTableCell" forIndexPath:indexPath];
    NSString *letter = self.resultKeys[indexPath.section];
    NSArray *array = self.resultSectionDict[letter];
    YMUserInfo *userInfo = array[indexPath.row];
    YMFriendInfo *info = array[indexPath.row];
    [cell bindData:userInfo];
    cell.showSelect = YES;
    NSString *userId = [YMIMClient sharedClient].userInfo.userId;
    if ([userId isEqualToString:info.friendId]) {
        cell.groupSelf = YES;
    }else{
        cell.groupSelf = NO;
    }
   
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 56;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


 
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 32.f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, self.view.frame.size.width, 32);
    view.backgroundColor = [UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectZero];
    title.frame = CGRectMake(13, 8, 15, 16);
    title.font = [UIFont systemFontOfSize:14.f];
    title.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];;
    [view addSubview:title];
    title.text = self.resultKeys[section];
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}
/**
 显示索引标题
 */
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.resultKeys;
}


#pragma mark Lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        [_tableView registerNib:[UINib nibWithNibName:@"ContactTableCell" bundle:nil] forCellReuseIdentifier:@"ContactTableCell"];
        [_tableView registerClass:[ContactTableCell class] forCellReuseIdentifier:@"ContactTableCell"];
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.allowsMultipleSelection = YES;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (UIButton *)confirmBtn {
    if (!_confirmBtn) {
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1] forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _confirmBtn.frame = CGRectMake(0, 0, 44, 44);
        [_confirmBtn addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
